import Foundation
import AppKit

public class WallpaperLibrary {
    public static let shared = WallpaperLibrary()
    
    private let libraryURL: URL
    private var resources: [URL] = []
    
    private init() {
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        libraryURL = documentsDirectory.appendingPathComponent("wallpaper_library")
        
        // 创建资源库目录
        try? FileManager.default.createDirectory(at: libraryURL, withIntermediateDirectories: true)
        
        // 加载现有资源
        loadResources()
    }
    
    private func loadResources() {
        guard let files = try? FileManager.default.contentsOfDirectory(
            at: libraryURL,
            includingPropertiesForKeys: nil
        ) else { return }
        
        resources = files.filter { url in
            let fileType = try? url.resourceValues(forKeys: [.contentTypeKey]).contentType
            return fileType?.conforms(to: .image) == true || fileType?.conforms(to: .movie) == true
        }
    }
    
    public func addResource(_ url: URL) async throws {
        let fileName = url.lastPathComponent
        let destinationURL = libraryURL.appendingPathComponent(fileName)
        
        // 如果文件已存在，生成唯一文件名
        var uniqueURL = destinationURL
        var counter = 1
        while FileManager.default.fileExists(atPath: uniqueURL.path) {
            let fileExtension = fileName.components(separatedBy: ".").last ?? ""
            let baseName = fileName.replacingOccurrences(of: "."+fileExtension, with: "")
            uniqueURL = libraryURL.appendingPathComponent("\(baseName)_\(counter).\(fileExtension)")
            counter += 1
        }
        
        // 处理网络URL
        if url.isFileURL {
            try FileManager.default.copyItem(at: url, to: uniqueURL)
        } else {
            // 下载网络图片
            let (data, _) = try await URLSession.shared.data(from: url)
            try data.write(to: uniqueURL)
        }
        
        resources.append(uniqueURL)
    }
    
    public func removeResource(_ url: URL) throws {
        try FileManager.default.removeItem(at: url)
        resources.removeAll { $0 == url }
    }
    
    public func getAllResources() -> [URL] {
        return resources
    }
    
    public func getImageResources() -> [URL] {
        return resources.filter { url in
            (try? url.resourceValues(forKeys: [.contentTypeKey]).contentType)?.conforms(to: .image) == true
        }
    }
    
    public func getVideoResources() -> [URL] {
        return resources.filter { url in
            (try? url.resourceValues(forKeys: [.contentTypeKey]).contentType)?.conforms(to: .movie) == true
        }
    }
}
